package br.com.honorato.bean;

import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import br.com.honorato.ejb.UserEJB;
import br.com.honorato.exception.EJBServiceException;
import br.com.honorato.model.UserApp;
import br.com.honorato.security.AuthenticationService;

@ManagedBean(name = "sessionBean")
@SessionScoped
public class SessionBean implements Serializable
{

	private static final long serialVersionUID = 1L;

	@EJB
	private UserEJB userEJB;
	private UserApp loggedUser;

	public SessionBean()
	{
		loggedUser = null;
	}

	@ManagedProperty(value = "#{authenticationService}")
	private AuthenticationService authenticationService; // injected Spring

	// defined service
	// for bikes

	public void setAuthenticationService(AuthenticationService authenticationService)
	{
		this.authenticationService = authenticationService;
	}

	public AuthenticationService getAuthenticationService()
	{
		return this.authenticationService;
	}

	public UserApp getLoggedUser()
	{

		if (loggedUser == null)
		{

			try
			{
				// TODO: Teste de get Message -- retirar
				getMsg("system.name");
				loggedUser = userEJB.getUserByLogin(FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName());

			}
			catch (EJBServiceException | NullPointerException err)
			{
				loggedUser = null;
			}
		}

		return loggedUser;
	}

	public void setLoggedUser(UserApp loggedUser)
	{
		this.loggedUser = loggedUser;
	}

	public boolean login(String username, String password)
	{
		return getAuthenticationService().login(username, password);
	}

	public void logout()
	{
		getAuthenticationService().logout();
		loggedUser = null;
	}

	public static String getMsg(String messageId)
	{

		FacesContext facesContext = FacesContext.getCurrentInstance();
		String msg = "";

		Locale locale = facesContext.getViewRoot().getLocale();
		ResourceBundle bundle5 = ResourceBundle.getBundle("messages", locale);

		try
		{
			msg = bundle5.getString(messageId);

		}
		catch (Exception e)
		{
		}

		return msg;
	}
}